package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SkuStockTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.EsSkuUpTo;
import static com.atguigu.common.to.es.EsSkuUpTo.Attrs;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import static com.atguigu.common.utils.Constant.ZERO_STR;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            queryWrapper.and(wrapper -> wrapper.eq("id", key).or().like("spu_name", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !StringUtils.equalsAnyIgnoreCase(catelogId, ZERO_STR)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !StringUtils.equalsAnyIgnoreCase(brandId, ZERO_STR)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuVo(SpuVo spuVo) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVo, spuInfoEntity);
        spuInfoEntity.initDate();
        this.save(spuInfoEntity);

        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        spuInfoDesc.setSpuId(spuInfoEntity.getId());
        spuInfoDesc.setDecript(String.join(",",spuVo.getDecript()));
        spuInfoDescService.save(spuInfoDesc);

        List<SpuImagesEntity> spuImageList = spuVo.getImages().stream().map(img -> new SpuImagesEntity(spuInfoEntity.getId(), img)).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(spuImageList)) {
            spuImagesService.saveBatch(spuImageList);
        }

        if (CollectionUtils.isNotEmpty(spuVo.getBaseAttrs())) {
            Map<Long, String> attrIdNameMap = attrService.list(new QueryWrapper<AttrEntity>().in("attr_id", spuVo.getBaseAttrs().stream().map(BaseAttrs::getAttrId).collect(Collectors.toList()))).stream().collect(Collectors.toMap(AttrEntity::getAttrId, AttrEntity::getAttrName, (o1, o2) -> o1));
            List<ProductAttrValueEntity> spuBaseAttrList = spuVo.getBaseAttrs().stream().map(baseAttr -> new ProductAttrValueEntity(spuInfoEntity.getId(), baseAttr.getAttrId(), attrIdNameMap.get(baseAttr.getAttrId()), baseAttr.getAttrValues(), baseAttr.getShowDesc())).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(spuBaseAttrList)) {
                productAttrValueService.saveBatch(spuBaseAttrList);
            }
        }
        //保存spu的积分信息：gulimall_sms -> sms_spu_bounds
        Bounds bounds = spuVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBound(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("保存spu积分信息异常");
        }

        //保存spu对应的sku信息
        List<Skus> skus = spuVo.getSkus();
        if (CollectionUtils.isNotEmpty(skus)) {
            skus.forEach(item -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                AtomicReference<String> skuDefaultImage = new AtomicReference<>("");
                List<SkuImagesEntity> skuImageList = item.getImages().stream().filter(images -> StringUtils.isNotBlank(images.getImgUrl())).map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    if (image.getDefaultImg() == 1) {
                        skuDefaultImage.set(image.getImgUrl());
                    }
                    BeanUtils.copyProperties(image, skuImagesEntity);
                    skuImagesEntity.setSkuId(skuId);
                    return skuImagesEntity;
                }).collect(Collectors.toList());

                if (CollectionUtils.isNotEmpty(skuImageList)) {
                    skuImagesService.saveBatch(skuImageList);
                }
                if (StringUtils.isNotBlank(skuDefaultImage.get())) {
                    skuInfoService.update(SkuInfoEntity.builder().skuDefaultImg(skuDefaultImage.get()).build(), new UpdateWrapper<SkuInfoEntity>().eq("sku_id", skuId));
                }

                List<Attr> attrList = item.getAttr();
                if (CollectionUtils.isNotEmpty(attrList)) {
                    List<SkuSaleAttrValueEntity> skuSaleAttrList = attrList.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuId);
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(skuSaleAttrList);
                }

                //sku的优惠、满减
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                R skuR = couponFeignService.saveSkuReduction(skuReductionTo);
                if (skuR.getCode() != 0) {
                    log.error("sku优惠、满减保存异常");
                }
            });
        }

    }

    @Override
    public void spuUp(Long spuId) throws IOException {
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        if (CollectionUtils.isEmpty(skuInfoEntityList)) {
            return;
        }
        String catelogName = categoryService.getById(skuInfoEntityList.get(0).getCatalogId()).getName();
        String brandName = brandService.getById(skuInfoEntityList.get(0).getBrandId()).getName();
        String brandImg = brandService.getById(skuInfoEntityList.get(0).getBrandId()).getLogo();
        List<ProductAttrValueEntity> attrValueEntityList = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = attrValueEntityList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        List<Long> actualAttrIds = attrService.list(new QueryWrapper<AttrEntity>().in("attr_id", attrIds).eq("search_type", 1)).stream().map(AttrEntity::getAttrId).collect(Collectors.toList());
        List<Attrs> attrs = attrValueEntityList.stream().filter(entity -> actualAttrIds.contains(entity.getAttrId())).map(entity -> {
            Attrs attr = new Attrs();
            BeanUtils.copyProperties(entity, attr);
            return attr;
        }).collect(Collectors.toList());

        R<List<SkuStockTo>> skuStockList = wareFeignService.queryStock(skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList()));
        ObjectMapper objectMapper = new ObjectMapper();
        List<SkuStockTo> skuStockToList = objectMapper.readValue(JSON.toJSONString(skuStockList.getData()), objectMapper.getTypeFactory().constructCollectionType(List.class, SkuStockTo.class));
        Map<Long, Boolean> skuStockResult = skuStockToList.stream().collect(Collectors.toMap(SkuStockTo::getSkuId, SkuStockTo::getHasStock, (o1, o2) -> o1));
        List<EsSkuUpTo> esSkuUpToList = skuInfoEntityList.stream().map(entity -> {
            EsSkuUpTo esSkuUpTo = new EsSkuUpTo();
            BeanUtils.copyProperties(entity, esSkuUpTo);
            esSkuUpTo.setSkuImg(entity.getSkuDefaultImg());
            esSkuUpTo.setSkuPrice(entity.getPrice());
            esSkuUpTo.setBrandImg(brandImg);
            esSkuUpTo.setBrandName(brandName);
            esSkuUpTo.setCatalogName(catelogName);
            esSkuUpTo.setHotScore(0L);
            esSkuUpTo.setAttrs(attrs);
            esSkuUpTo.setHasStock(BooleanUtils.isTrue(skuStockResult.get(entity.getSkuId())));
            return esSkuUpTo;
        }).collect(Collectors.toList());
        R r = searchFeignService.bulkProduct(esSkuUpToList);
        if (r.getCode() == 0) {
            baseMapper.update(new SpuInfoEntity(ProductConstant.SpuStatusEnum.SPU_UP.getCode()), new UpdateWrapper<SpuInfoEntity>().eq("id", spuId));
        }else{
            //TODO 远程调用失败  需要重复调用（那么如何保证接口幂等性）
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        //先查询sku表里的数据
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);

        //获得spuId
        Long spuId = skuInfoEntity.getSpuId();

        //再通过spuId查询spuInfo信息表里的数据
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);

        //查询品牌表的数据获取品牌名
        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        spuInfoEntity.setBrandName(brandEntity.getName());

        return spuInfoEntity;
    }
}
